﻿@using CleanArchitecture.Core.Helper
@using CleanArchitecture.Infrastructure.Models.Business.Advertises

@model AdvertiseBannerModel
@{
    Layout = "_BackendLayout";
    ViewData["Title"] = ViewBag.PageTitle as string;
    var AvailableDisplayType = ViewBag.AvailableDisplayType as IList<SelectListItem> ?? null;
    var AvailableAdvType = ViewBag.AvailableAdvType as IList<SelectListItem> ?? null;
}
@section csslinks {
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="~/js/vuecomponentes/vueuploadlist/vueuploadlist.css" />
    <link rel="stylesheet" href="~/js/vuecomponentes/vuelinktable/vuelinktable.css" />
}
@section cssstyles {
    <style type="text/css">
        body {
            margin: 5px !important;
            display: flex;
            flex: auto;
            flex-direction: column;
            min-height: 0;
            background: #f0f2f5;
        }

        .layui-tab-title {
            padding-left: 20px;
        }

        .layui-form-switch {
            margin-top: 6px;
            height: 25px;
        }

        .layui-input-inline {
            width: 320px !important;
        }

        .layui-form-label {
            width: 150px !important;
        }

        .layui-input-block {
            margin-left: 150px !important;
        }

        .layui-slider-input {
            top: 0 !important;
        }

        .orderSlider {
            padding-top: 15px;
        }

        .layui-btn {
            margin-left: 10px;
        }
    </style>
}
<div class="layui-main" style="background-color: #fff; width: 100%; padding: 0 20px;">
    <form class="layui-form" action="">
        <div class="layui-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">基础信息</li>
                <li>内容设置</li>
            </ul>

            <div class="layui-tab-content">
                <!--基础信息-->
                <div class="layui-tab-item layui-show">
                    <div class="layui-form-item">
                        <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerName))</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" name="@Model.nameof(p => p.AdvBannerName)" lay-verify="required" placeholder="请输入广告栏位名称" value="@Model.AdvBannerName" />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerDisplayType))</label>
                        <div class="layui-input-inline">
                            <select asp-for="AdvBannerDisplayType" asp-items="@AvailableDisplayType" lay-verify="required">
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerType))</label>
                        <div class="layui-input-inline">
                            <select asp-for="AdvBannerType" asp-items="@AvailableAdvType" lay-verify="required" lay-filter="AdvTypeSelect">
                            </select>
                        </div>
                        <div class="layui-form-mid layui-word-aux">类型提交保存后不能再更改</div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerWidth))</label>
                            <div class="layui-input-inline">
                                <input type="number" name="@Model.nameof(p => p.AdvBannerWidth)" value="@Model.AdvBannerWidth" placeholder="请输入数字即可" maxlength="20" lay-verify="required" autocomplete="off" class="layui-input" />
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerHeight))</label>
                            <div class="layui-input-inline">
                                <input type="number" name="@Model.nameof(p => p.AdvBannerHeight)" value="@Model.AdvBannerHeight" placeholder="请输入数字即可" maxlength="20" lay-verify="required" autocomplete="off" class="layui-input" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.StartTime))</label>
                            <div class="layui-input-inline">
                                <input type="text" id="StartTime" name="@Model.nameof(p => p.StartTime)" value="@Model.StartTime" class="layui-input" />
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.EndTime))</label>
                            <div class="layui-input-inline">
                                <input type="text" id="EndTime" name="@Model.nameof(p => p.EndTime)" value="@Model.EndTime" class="layui-input" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.DisplayOrder))</label>
                        <div class="layui-input-inline">
                            <div id="orderSlider" class="orderSlider"></div>
                            <input type="text" class="layui-hide" name="@Model.nameof(m => m.DisplayOrder)" value="@Model.DisplayOrder" />
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<AdvertiseBannerModel>(m => m.AdvBannerDescription))</label>
                        <div class="layui-input-inline">
                            <textarea name="@Model.nameof(m => m.AdvBannerDescription)" class="layui-textarea" style="min-height: 60px;" placeholder="简要说明一下，广告的位置，作用等。"></textarea>
                        </div>
                    </div>
                    <div style="width: 100%; height: 50px; line-height: 50px; float: left;"></div> <!--占位符，防止底部固定提交栏遮挡最下层区域-->
                </div>
                <!--内容设置 -->
                <div class="layui-tab-item">
                    <!-- 友情链接 轮播图 固定位置单图-->
                    <div id="linktable" class="layui-row">
                        <link-table :item-data="itemData" ref="linktable" />
                    </div>
                    <!-- 图形列表-->
                    @*<div id="ImageList" class="layui-row">
                            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                                <upload-list ref="uploadlist"/>
                            </div>
                            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                                移动：6/12 | 平板：6/12 | 桌面：4/12
                            </div>
                        </div>*@
                </div>
            </div>
        </div>

        <input type="text" name="@Model.nameof(m => m.Id)" value="@Model.Id" class="layui-hide" />
        <div class="layui-form-item footerbar">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-filter="editAdvBanner" lay-submit>提交</button>
            </div>
        </div>
    </form>
</div>

@section scripts {
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="~/js/vuecomponentes/vueuploadlist/vueuploadlist.js"></script>
    <script src="~/js/vuecomponentes/vuelinktable/vuelinktable.js"></script>
    <script type="text/javascript">
    $(function () {
        layui.use(['element', 'notice', 'layer', 'laydate', 'form', 'slider', 'iziToast'], function () {
            var form = layui.form,
                element = layui.element,
                notice = Util.notice !== null && Util.notice() !== null
                       ? Util.notice() : layui.notice,
                layer = layui.layer,
                slider = layui.slider,
                laydate = layui.laydate,
                iziToast = layui.iziToast,
                lodash = _;
            var $advType = $("select[name='AdvBannerType'] option:checked");
            //友情链接 (图片链接,文字链接)
            //轮播图
            //固定位置单图  统一存储格式
            var AdvLinkItem = {
                options: {
                    advType: "",       //广告使用类型，与后台AdvBannerType数据一致
                    isImageLink: true, //是否图片链接 当为友情链接 文字链接时为false
                    limitNum: 0,       //数量限制，当为固定位置单图时为1，0则无数量限制
                    initData: false    //是否有初始数据，true则初使数据替换items,false则items为模板数据
                },
                items: [{
                    id: 0,             //如果是图片链接则保存上传图片Id，文字链接为0
                    imgUrl: '',        //如果是图片链接存储图片Url
                    title: '',         //链接(或图片)显示名称
                    desc: '',          //链接(或图片)描述信息
                    contents: '',      //链接(或图片)文本内容
                    url: '#',          //跳转链接地址
                    target: '_no',     //地址链接跳转方式 _blank新窗口 _self页内跳转 _no不跳转
                    sort: 1            //排序号
                }]
            };
            var updateAdvLinkItem = function (advtype) {
                if (typeof advtype !== "string") {
                    iziToast.error({
                        title: '消息通知',
                        message: "数据更新失败：无效的使用类型"
                    });
                    return;
                }
                if (advtype === "GridLayout") {  //复杂的栅格图片矩阵单独设置

                } else {
                    AdvLinkItem.options.advType = advtype;
                    AdvLinkItem.options.isImageLink = (advtype === "TextLinks") ? false : true;
                    //固定位置单图限制添加数量
                    AdvLinkItem.options.limitNum = (advtype === "StaticImage") ? 1 : 0;
                    var itemjsonstr = @(!string.IsNullOrEmpty(Model.ItemsJson) ? Html.Raw(Model.ItemsJson) : Html.Raw("[]"));
                    if (itemjsonstr.length === 0)
                        AdvLinkItem.options.initData = false;
                    else {
                        AdvLinkItem.options.initData = true;
                        AdvLinkItem.items = itemjsonstr; //JSON.parse(itemjsonstr);
                    }
                }
            };
            var initPageComponent = function () {
                //滑动组件
                let $order = $("input[name=@Model.nameof(m => m.DisplayOrder)]");
                slider.render({
                    elem: '#orderSlider'
                    , min: 1
                    , max: 150
                    , input: true //输入框
                    , theme: '#1E9FFF' //主题色
                    , value: $order.val()
                    , change: function (value) {
                        $order.val(value);
                    }
                });
                updateAdvLinkItem($advType.val());
                //日期初始化
                laydate.render({
                    elem: '#StartTime'
                    , format: 'yyyy-MM-dd'
                    , trigger: 'click'
                    , value: '@(Model.StartTime.HasValue ? Model.StartTime.Value.ToString("yyyy-MM-dd") : "")'
                    , isInitValue: true
                    , done: function (value, date) {
                        if (value && $("#EndTime").val()) {
                            if (value > $("#EndTime").val()) {
                                /*开始时间大于结束时间时，清空结束时间*/
                                iziToast.error({
                                    title: '消息通知',
                                    message: "开始时间不应晚于结束时间"
                                });
                                $("#StartTime").val("");
                            }
                        }
                    }
                });
                laydate.render({
                    elem: '#EndTime'
                    , format: 'yyyy-MM-dd'
                    , trigger: 'click'
                    , value: '@(Model.EndTime.HasValue ? Model.EndTime.Value.ToString("yyyy-MM-dd") : "")'
                    , isInitValue: true
                    , done: function (value, date) {
                        if (value && $("#StartTime").val()) {
                            if (value < $("#StartTime").val()) {
                                /*开始时间大于结束时间时，清空结束时间*/
                                iziToast.error({
                                    title: '消息通知',
                                    message: "结束时间不应早于结束时间"
                                });
                                $("#EndTime").val("");
                            }
                        }
                    }
                });
            };
            initPageComponent();

            //内容设置
            //Vue.component('upload-list', vueuploadlist); //from vueuploadlist.js
            var vm = new Vue({
                el: '#linktable',
                components: {
                    //'upload-list': vueuploadlist
                    'link-table': vuelinktable
                },
                data: {
                    itemData: AdvLinkItem
                },
                methods: {
                    updateLinkTable: function (newdata) {
                        updateAdvLinkItem(newdata);
                        this.itemData = AdvLinkItem;
                    },
                    getLinkTableData: function () {
                        return this.$refs.linktable.tableData;
                    }
                }
            });
            form.on('select(AdvTypeSelect)', function (data) {
                var $ModelId = $("input[name='@Model.nameof(m => m.Id)']");
                if (parseInt($ModelId.val()) > 0) {
                    iziToast.error({
                        title: '消息通知',
                        message: "已提交保存广告栏不支持类型修改"
                    });
                    $(data.elem).val("@Model.AdvBannerType");
                    form.render('select');
                    return false;
                } else vm.updateLinkTable(data.value);
            });

            form.on("submit(editAdvBanner)", function (data) {
                var postJson = data.field,
                    //advtype = $advType.val(),
                    itemsJsonArr = null;
                if ((postJson.StartTime.length > 0 && postJson.EndTime.length === 0)
                    || (postJson.EndTime.length > 0 && postJson.StartTime.length === 0)) {
                    iziToast.error({
                        title: '消息通知',
                        message: "请选择广告投放时间或都不选"
                    });
                }
                if (postJson.AdvBannerType !== "GridLayout") {
                    itemsJsonArr = vm.getLinkTableData();
                    //console.log(postJson);
                    if (postJson.AdvBannerType !== 'TextLinks' && itemsJsonArr && itemsJsonArr.length > 0) {
                        if (lodash.findIndex(itemsJsonArr, function (o) { return o.id === 0; }) >= 0) {
                            iziToast.error({
                                title: '消息通知',
                                message: "内容区有新增未编辑的项目，请删除或编辑后再提交保存"
                            });
                            return false;
                        }
                    }
                }
                else {

                }
                if (!lodash.isArray(itemsJsonArr)) {
                    iziToast.error({
                        title: 'Bug Report',
                        message: "提交数据有误，请联系系统管理员"
                    });
                    return false;
                }
                postJson.ItemsJson = itemsJsonArr.length > 0
                    ? JSON.stringify(itemsJsonArr)
                    : null;
                var index = layer.load(2, { time: 10 * 1000 });
                httpapi.fetchPost('/api/backend/business/advertisemanage/edit', postJson).then(res => {
                    layer.close(index);
                    if (!httpapi.checkResponse(res))
                        //输入信息校验错误
                        notice.error(res.message);
                    else {//Success
                        notice.success(res.message);
                        Util.CloseMainWindow();
                    }
                }).catch(error => {
                    notice.error("对不起，出现未知错误，请您联系系统管理员！");
                    console.log(error);
                });
                return false;
            });
        });
    });
    </script>
}